package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsAdminMapper;
import com.qf.mapper.DtsPermissionMapper;
import com.qf.mapper.DtsRoleMapper;
import com.qf.pojo.DtsAdmin;
import com.qf.pojo.DtsPermission;
import com.qf.pojo.DtsRole;
import com.qf.service.DtsRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @version v1.0.0
 * @Description:
 * @author: 姜红凯
 * @date: 2022.02.18
 * @since 1.0
 */
@Service
public class DtsRoleServiceImpl implements DtsRoleService {

    @Autowired
    DtsRoleMapper roleMapper;

    @Override
    public Set<String> findRolesByRoleIds(Integer[] roleIds) {
        LambdaQueryWrapper<DtsRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(DtsRole::getId, roleIds).select(DtsRole::getName);

        List<DtsRole> roles = roleMapper.selectList(wrapper);
        //使用lambda 把list中的数据 存储到set集合中
        //stream: 流化
        //map : 映射关系
        //collect： 指定要转换的类型
        //role 表示list中的每一个元素
        Set<String> roleNames = roles.stream().map(role -> {
            return role.getName();
        }).collect(Collectors.toSet());

        return roleNames;
    }

    @Override
    public List<DtsRole> findAll() {
        List<DtsRole> roles = roleMapper.selectList(null);
        return roles;
    }

    @Override
    public IPage<DtsRole> queryPage(Integer page, Integer limit, String sort, String order, String rolename) {

        //分页参数
        IPage<DtsRole> iPage = new Page<>(page,limit);
        //其他条件
        QueryWrapper<DtsRole> wrapper = new QueryWrapper();
        //判断是否为null
        if(!StringUtils.isEmpty(rolename)){
            //不为空，进行模糊查询
            wrapper.like("name",rolename);
        }
        wrapper.eq("deleted",false);

        //排序条件
        if(!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)){
            if(order.equals("desc")){
                wrapper.orderByDesc(sort);
            }else {
                wrapper.orderByAsc(sort);
            }
        }
        roleMapper.selectPage(iPage,wrapper);
        return iPage;
    }

    @Override
    public DtsRole insert(DtsRole role) {
        role.setAddTime(new Date());
        role.setUpdateTime(new Date());
        role.setDeleted(false);
        role.setEnabled(true);
        roleMapper.insert(role);
        return role;
    }

    @Override
    public boolean checkRole(String name) {
        LambdaQueryWrapper<DtsRole> wrapper = new LambdaQueryWrapper<>();
        //根据name查询
        wrapper.eq(DtsRole::getName,name);

        Integer count = roleMapper.selectCount(wrapper);
        //判断count 是否等于0   (如果是0 则0!=0 返回false)  (如果是1 则1!=0 返回true)
        return count != 0;
    }

    @Override
    public DtsRole update(DtsRole role) {
        role.setUpdateTime(new Date());
        roleMapper.updateById(role);
        return role;
    }

    @Override
    public void deleteById(Integer id) {

        roleMapper.deleteById(id);
    }

    @Autowired
    DtsPermissionMapper permissionMapper;

    @Autowired
    DtsAdminMapper adminMapper;

    @Override
    public boolean checkRelationRole(Integer id) {
        //查询是否被权限表关联
        LambdaQueryWrapper<DtsPermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtsPermission::getRoleId,id);
        Integer count = permissionMapper.selectCount(wrapper);
        if(count > 0){
            return false;
        }

        //把所有的管理员都查询出来，判断管理员的角色id中是否存在 该角色id,如果存在返回false ,不存在返回true
        //拿到所有admin
        List<DtsAdmin> adminList = adminMapper.selectList(null);
        for(DtsAdmin admin : adminList){
            //最少有一个角色
           if(admin.getRoleIds() != null &&  admin.getRoleIds().length > 0){
               //循环每一个roleId
               for (Integer roleId : admin.getRoleIds()) {
                   //相等说明角色存在,不能删除
                   if(roleId == id){
                       return false;
                   }
               }
           }

        }
        //上面都不成立，说明不存在，能删除
        return true;
    }

    @Override
    public boolean checkIsSuperManager(Integer roleId) {
        DtsRole role = roleMapper.selectById(roleId);
        if(role.getName() != null && role.getName().equals("超级管理员")){
            return true;
        }
        return false;
    }



    @Override
    public void updatePermissions(Integer roleId, List<String> permissions) {
        //1.删除该角色的所有权限
        LambdaQueryWrapper<DtsPermission> wrapper = new LambdaQueryWrapper();
        wrapper.eq(DtsPermission::getRoleId,roleId);
        permissionMapper.delete(wrapper);

        //2.添加角色和权限新的关系
        if(permissions != null && permissions.size() > 0){
            for (String permission : permissions) {
                DtsPermission perm = new DtsPermission();
                perm.setRoleId(roleId);
                perm.setPermission(permission);
                perm.setAddTime(new Date());
                perm.setUpdateTime(new Date());
                perm.setDeleted(false);
                permissionMapper.insert(perm);
            }
        }
    }
}